/**
 * Created by ltx on 2017/9/21.
 */
const express=require('express');
const mysql=require('mysql');


var db=mysql.createPool({host: 'localhost', user: 'root', password: '123456*', database: 'aigourenshi'});

module.exports=function (){
    var router=express.Router();

    router.post('/userlogin', (req, res)=>{
        console.log(req.session);
        var username=req.body.username;
        var password=req.body.password;

        //用户是否为空
        if (username==''){
            res.json({
                code:1,
                message:'用户名不能为空'
            });
            return;
        }
        //密码是否为空
        else if (password==''){
            res.json({
                code:2,
                message:'密码不能为空'
            });
            return;
        }
        else {
            db.query(`SELECT * FROM user_table WHERE name=${req.body.username}`,(err,data)=>{
                if (err){
                    res.status(500).send('数据库错误').end();
                }
                else {
                    if (data.length==0){
                        res.json({
                            code:3,
                            message:'没有找到该用户'
                        });
                        return;
                    }
                    else {
                        if (data[0].password==password){
                            req.session.sign =  true;
                            req.session.name = req.body.username;
                            res.json({
                                code:0,
                                message:'登录成功',
                                username: req.body.username
                            });
                            return;
                        }
                        else {
                            res.json({
                                code:4,
                                message:'密码不正确'
                            });
                            return;
                        }
                    }
                }
            })
        }
    });

    return router;
}